import { config } from "../../../config"

const app = getApp()

Page({
	data: {
		userInfo: "",
		schoolConfig: "",
	},
	onLoad() {
		this.initData()
	},
	initData() {
		this.setData({
			userInfo: wx.getStorageSync("userInfo"),
			schoolConfig: wx.getStorageSync("schoolConfig"),
		})
	},
	/**
	 * @see 触发解除绑定
	 */
	loginOut() {
		wx.showModal({
			title: "提示",
			content: "确定要解除绑定吗?",
			confirmColor: "#2172ed",
			success: (res) => {
				if (res.confirm) {
					this.loginOutApi()
				}
			},
		})
	},
	/**
	 * @see 解除绑定API
	 */
	loginOutApi() {
		wx.showLoading({ mask: true, title: "正在处理..." })
		// 企业微信环境
		if (wx.qy) {
			wx.qy.login({
				success: (res) => {
					const request = { code: res.code }
					this.loginApi(request)
				},
				fail: (err) => {
					wx.showModal({
						title: "提示",
						content: "请重试",
						showCancel: false,
					})
				},
			})
		} else {
			wx.login({
				success: (res) => {
					const request = { code: res.code }
					this.loginApi(request)
				},
				fail: (err) => {
					wx.showModal({
						title: "提示",
						content: "请重试",
						showCancel: false,
					})
				},
			})
		}
	},
	refreshUserInfo() {
		wx.showLoading({ mask: true, title: "更新中~" })
		wx.login({
			success: (res) => {
				const request = { code: res.code, loginType: 1 }
				wx.$API["login/login"](request)
					.then((result) => {
						const { token, data, schoolConfig } = result
						app.storageData(token, data[0], schoolConfig)
						wx.hideLoading()
						wx.showToast({ title: "刷新成功", icon: "success" })
						this.initData()
					})
					.catch((err) => {
						if (err === "-3001") {
							// 用户没有绑定过微信
							wx.reLaunch({
								url: config.loginPage,
							})
						} else {
							console.log("login/checkLogin", err)
						}
					})
			},
			fail: (err) => {
				wx.showModal({
					title: "提示",
					content: "获取code失败,请退出微信后重试",
					showCancel: false,
				})
			},
		})
	},
	loginApi(request) {
		wx.$API["login/loginOut"](request)
			.then((result) => {
				const userInfo = wx.getStorageSync("userInfo")
				const schoolConfig = wx.getStorageSync("schoolConfig")
				// 统一身份认证回调地址
				const unifiedAuthUrl = wx.getStorageSync("unifiedAuthUrl")
				const userLoginCache = {
					userId: userInfo.userId,
					// schoolCode: schoolConfig.schoolCode,
					// schoolName: schoolConfig.schoolName,
					...schoolConfig,
				}
				wx.clearStorageSync()
				// 记录最后一次退出时的信息，下次登录时直接填充上
				wx.setStorage({ key: "userLoginCache", data: userLoginCache })
				wx.setStorage({ key: "unifiedAuthUrl", data: unifiedAuthUrl })
				wx.hideLoading()
				app.globalData.autoQyLogin = false
				wx.reLaunch({
					url: config.loginPage,
				})
				app.globalData.extraData = null
				wx.showToast({
					title: "解绑成功",
					icon: "none",
					duration: 2000,
				})
			})
			.catch((err) => {
				wx.showToast({
					title: err,
					icon: "none",
					duration: 2000,
				})
			})
	},
})
